package com.sky.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.constant.StatusConstant;
import com.sky.dto.BusinessDataAggrDTO;
import com.sky.dto.DeshAggrDTO;
import com.sky.dto.OrdersAggrDTO;
import com.sky.dto.SetmealAggrDTO;
import com.sky.entity.Orders;
import com.sky.exception.BaseException;
import com.sky.mapper.DeshAggrDTOMapper;
import com.sky.mapper.OrdersAggrDTOMapper;
import com.sky.mapper.SetmealAggrDTOMapper;
import com.sky.mapper.ShopAggrDTOMapper;
import com.sky.result.Result;
import com.sky.service.IOrdersService;
import com.sky.service.IWorkService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @BelongsProject: sky-take-out
 * @Author: XieMingHui
 * @CreateTime: 2023-11-21  17:26
 * @Description: 工作台
 * @Version: 1.0
 */
@Service
@Slf4j
public class IWorkServiceImpl implements IWorkService {

    @Resource
    private SetmealAggrDTOMapper setmealAggrDTOMapper;
    @Resource
    private DeshAggrDTOMapper deshAggrDTOMapper;

    @Resource
    private ShopAggrDTOMapper shopAggrDTOMapper;
    @Resource
    private OrdersAggrDTOMapper ordersAggrDTOMapper; //聚合类mapper
    @Resource
    private IOrdersService iOrdersService;
    /**
     * 查询今日运营数据
     *
     * @author: XieMingHui
     * @param: []
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<BusinessDataVO> businessData() {
        LocalDate now = LocalDate.now();
        // 当天新注册的用户
        Integer newUsers = shopAggrDTOMapper.userRegistraCount(now);
        if (newUsers==null){
            newUsers=0;
        }
        // 当天订单和营业额
        BusinessDataAggrDTO businessData = shopAggrDTOMapper.BusinessData(now, Orders.COMPLETED);
        Double turnover = businessData.getTurnover();
        Integer validOrderCount = businessData.getValidCount();
        // 平均客单价
        Double unitPrice = null;
        try {
            // 计算单价,四舍五入2位
            unitPrice = NumberUtil.div(turnover, validOrderCount,2).doubleValue();
        } catch (Exception e) {
            // 没有订单,会出现除0异常
            throw new BaseException("没有完成订单数据");
        }
        // 总订单量
        Integer orderCount = iOrdersService.lambdaQuery().ge(Orders::getOrderTime, now).count();
        // 订单完成率
        Double orderCompletionRate = null;
        try {
            orderCompletionRate = NumberUtil.div(validOrderCount, orderCount).doubleValue();
        } catch (Exception e) {
            throw new BaseException("没有完成订单数据");
        }
        BusinessDataVO businessDataVO = BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
        log.info("当日数据统计=====>{}",businessDataVO);
        return Result.success(businessDataVO);
    }

    /**
     * 查询套餐总
     *
     * @author: XieMingHui
     * @param: []
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<SetmealOverViewVO> overviewSetmeals() {
        QueryWrapper<SetmealAggrDTO> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(SetmealAggrDTO::getStatus, SetmealAggrDTO::getCount)
                .groupBy(SetmealAggrDTO::getStatus);
        List<SetmealAggrDTO> list = setmealAggrDTOMapper.selectList(wrapper);
        log.info("状态订单统计{}", list);
        // 分组结果封装到Map集合,因为可以多字段分组,所以返回的封装多个map集合的List集合
        if (list.size() == 0) {
            throw new BaseException("没有此类套餐");
        }
        Map<Integer, Integer> collect = list.stream()
                .collect(Collectors.toMap(SetmealAggrDTO::getStatus, SetmealAggrDTO::getCount));
        return Result.success(new SetmealOverViewVO(
                collect.get(StatusConstant.ENABLE),
                collect.get(StatusConstant.DISABLE)));
    }

    /**
     * 查询菜品总览
     *
     * @author: XieMingHui
     * @param: []
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<DishOverViewVO> overviewDishes() {
        QueryWrapper<DeshAggrDTO> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(DeshAggrDTO::getStatus, DeshAggrDTO::getCount)
                .groupBy(DeshAggrDTO::getStatus);
        List<DeshAggrDTO> list = deshAggrDTOMapper.selectList(wrapper);
        log.info("状态订单统计{}", list);
        // 分组结果封装到Map集合,因为可以多字段分组,所以返回的封装多个map集合的List集合
        if (list.size() == 0) {
            throw new BaseException("没有此类菜品");
        }
        Map<Integer, Integer> collect = list.stream()
                .collect(Collectors.toMap(DeshAggrDTO::getStatus, DeshAggrDTO::getCount));
        return Result.success(new DishOverViewVO(
                collect.get(StatusConstant.ENABLE),
                collect.get(StatusConstant.DISABLE)));
    }

    /**
     * 查询订单管理数据
     *
     * @author: XieMingHui
     * @param: []
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<OrderOverViewVO> overviewOrders() {
        QueryWrapper<OrdersAggrDTO> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(OrdersAggrDTO::getStatus, OrdersAggrDTO::getCount)
                .groupBy(OrdersAggrDTO::getStatus);
        List<OrdersAggrDTO> list = ordersAggrDTOMapper.selectList(wrapper);
        if (list.size() == 0) {
            throw new BaseException("没有此类订单");
        }
        // 分组结果封装到Map集合,因为可以多字段分组,所以返回的封装多个map集合的List集合
        Map<Integer, Integer> collect = list.stream()
                .collect(Collectors.toMap(OrdersAggrDTO::getStatus, OrdersAggrDTO::getCount));
        if (collect.size() == 0) {
            throw new BaseException("没有此类订单");
        }
        log.info("状态订单统计=>{}", collect);
        // 判断状态是否有值,如果没有,则赋值为0,再封装返回
        OrderOverViewVO orderOverViewVO = getOrderOverViewVO(collect);
        return Result.success(orderOverViewVO);

    }

    /**
     * 判断状态是否有值,如果没有,则赋值为0,再封装返回
     *
     * @author: XieMingHui
     * @param: [collect]
     * @return: com.sky.vo.OrderOverViewVO
     **/
    private OrderOverViewVO getOrderOverViewVO(Map<Integer, Integer> collect) {
        Integer waitingOrders = collect.get(Orders.TO_BE_CONFIRMED);
        if (waitingOrders == null) {
            waitingOrders = 0;
        }
        Integer deliveredOrders = collect.get(Orders.CONFIRMED);
        if (deliveredOrders == null) {
            deliveredOrders = 0;
        }
        Integer completedOrders = collect.get(Orders.COMPLETED);
        if (completedOrders == null) {
            completedOrders = 0;
        }
        Integer cancelledOrders = collect.get(Orders.CANCELLED);
        if (cancelledOrders == null) {
            cancelledOrders = 0;
        }
        Integer allOrders = waitingOrders + deliveredOrders + completedOrders + cancelledOrders;
        OrderOverViewVO orderOverViewVO = new OrderOverViewVO();
        orderOverViewVO.setWaitingOrders(waitingOrders);
        orderOverViewVO.setDeliveredOrders(deliveredOrders);
        orderOverViewVO.setCompletedOrders(completedOrders);
        orderOverViewVO.setCancelledOrders(cancelledOrders);
        orderOverViewVO.setAllOrders(allOrders);
        return orderOverViewVO;
    }
}
